//
//  UIToolHelper.swift
//  CocoProject
//
//  Created by Vill on 2023/11/13.
//

import Foundation
import UIKit

struct UIToolHelper{
    
    static func currentViewController() -> UIViewController? {
        var win: UIWindow?
        if #available(iOS 13, *) {
            let windowScene = UIApplication.shared.connectedScenes.first
            guard let windowScene = windowScene as? UIWindowScene, windowScene.activationState == .foregroundActive else {
                return nil
            }
            win = windowScene.windows.first
        } else {
            win = UIApplication.shared.keyWindow
        }
       
        guard let win = win else {
            return nil
        }
        
        var window = win
        if window.windowLevel == .normal {
            var windows: [UIWindow] = []
            
            if #available(iOS 15, *) {
                windows = UIApplication.shared.connectedScenes.map{$0 as? UIWindowScene}.compactMap{$0}.first?.windows ?? []
            } else {
                windows = UIApplication.shared.windows
            }
            
            for tmpWin in windows {
                if tmpWin.windowLevel == .normal {
                    window = tmpWin
                    break
                }
            }
        }
        var rootVc = window.rootViewController
        var activityVc: UIViewController?
        while true {
            if let vc = rootVc {
                if let vc = vc as? UINavigationController {
                    activityVc = vc.visibleViewController
                } else if let vc = vc as? UITabBarController {
                    activityVc = vc.selectedViewController
                } else if let vc = vc.presentedViewController {
                    activityVc = vc
                } else {
                    break
                }
                
                rootVc = activityVc
            } else {
                break
            }
        }
        return activityVc
    }
    
    static func makeToast(_ msg:String?) {
        DispatchQueue.main.async {
            UIApplication.shared.getKeyWindow()?.makeToast(msg)
        }
    }
    
    static func showHUD() {
        DispatchQueue.main.async {
            UIApplication.shared.getKeyWindow()?.makeToastActivity(.center)
        }
       
    }
    static func hideHUD() {
        DispatchQueue.main.async {
            UIApplication.shared.getKeyWindow()?.hideToastActivity()
        }
    }
}
